package com.java.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.java.entity.BsCourse;
import com.java.entity.BsCourseTarget;
import com.java.entity.BsScore;
import com.java.entity.BsScoreRecord;
import com.java.entity.BsStudent;
import com.java.entity.dtoVo.BsStudentDto;
import com.java.entity.ext.BsScoreRecordVo;
import com.java.entity.ext.BsScoreVo;
import com.java.mapper.BsCourseMapper;
import com.java.mapper.BsCourseTargetMapper;
import com.java.mapper.BsScoreMapper;
import com.java.mapper.BsScoreRecordMapper;
import com.java.mapper.BsStudentMapper;
import com.java.service.BsStudentService;
import com.java.util.MyCons;
import com.java.util.MyMap;
import com.java.util.MyTools;
import com.java.util.resp.BaseRespone;
import com.java.util.resp.TableRespone;
import com.java.util.servlet.ServletUtil;

@Service
public class BsStudentServiceImpl implements BsStudentService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired private BsStudentMapper studentMapper;
    @Autowired private BsScoreMapper scoreMapper;
    @Autowired private BsCourseMapper courseMapper;
    @Autowired private BsScoreRecordMapper recordMapper;
    @Autowired private BsCourseTargetMapper targetMapper;

	@Override
	public BaseRespone updateByAdmin(BsStudent student) {
		BsStudent info = studentMapper.selectByInfo(new BsStudent().setStudentNumber(student.getStudentNumber()));
		if(null != info && !info.getStudentId().equals(student.getStudentId())) {
			return BaseRespone.error("该学号已被使用");
		}
		int row = studentMapper.updateSelective(student);
		if(row > 0) {
			return BaseRespone.success("修改成功");
		}
		return BaseRespone.error("修改失败");
	}

	@Override
	public BaseRespone login(String number, String password) {
		BsStudent info = studentMapper.selectByInfo(new BsStudent().setStudentNumber(number));
		if(null == info) {
			return BaseRespone.error("该学号不存在");
		}
		if(info.getStudentActive() == 0) {
			return BaseRespone.error("该学号未生效");
		}
		if(info.getStudentActive() == 2) {
			return BaseRespone.error("您已离校");
		}
		if(!info.getStudentPassword().equals(password)) {
			return BaseRespone.error("密码错误");
		}
		ServletUtil.getSession().setAttribute(MyCons.USER_ROLE, info);
		return BaseRespone.success("登陆成功");
	}

	@Override
	public BaseRespone register(String number, String password, String name, String college, String classs,
			String major, Date intake) {
		BsStudent info = studentMapper.selectByInfo(new BsStudent().setStudentNumber(number));
		if(null != info) {
			return BaseRespone.error("该学号已被注册");
		}
		info = new BsStudent();
		info.setStudentId(MyTools.getUUID())
		.setStudentNumber(number)
		.setStudentPassword(password)
		.setStudentName(name)
		.setStudentSex("未知")
		.setStudentCollege(college)
		.setStudentClass(classs)
		.setStudentMajor(major)
		.setStudentIntakeTime(intake)
		.setStudentTime(new Date())
		.setStudentActive(0);
		int row = studentMapper.insertSelective(info);
		if(row == 0) {
			return BaseRespone.error("注册失败");
		}
		return BaseRespone.success("注册成功，等待管理员审核");
	}

	@Override
	public TableRespone getStudentList(String number, String name, Integer active, int page, int size) {
		MyMap mm = new MyMap()
				.put("studentNumber", number)
				.put("studentName", name)
				.put("studentActive", active)
				.put("studentDelete", "0");
		int offset = TableRespone.getOffset(page, size);
		List<BsStudent> list = studentMapper.selectAll(mm, offset, size);
		List<BsStudent> count = studentMapper.selectAll(mm, 0, 0);
		return new TableRespone(list, count.size());
	}

	@Override
	public BaseRespone studentActive(String id, Integer active) {
		int row = studentMapper.updateSelective(new BsStudent().setStudentId(id).setStudentActive(active));
		if(row > 0) {
			return BaseRespone.success("设置成功");
		}
		return BaseRespone.error("设置失败");
	}


	@Override
	public BsStudent getStudent(String studentId) {
		return studentMapper.selectByKey(studentId);
	}

	@Override
	public BaseRespone update(BsStudent student) {
		BsStudent info = studentMapper.selectByKey(student.getStudentId());
		info.setStudentName(student.getStudentName())
		.setStudentCollege(student.getStudentCollege())
		.setStudentClass(student.getStudentClass())
		.setStudentMajor(student.getStudentMajor())
		.setStudentMobile(student.getStudentMobile())
		.setStudentEmail(student.getStudentEmail())
		.setStudentSex(student.getStudentSex());
		int row = studentMapper.updateSelective(info);
		if(row > 0) {
			return BaseRespone.success("设置成功");
		}
		return BaseRespone.error("设置失败");
	}
    
	@Override
	public TableRespone getScores(String studentId, String title, String typeId, int page, int size) {
		MyMap mm = new MyMap()
				.put("scoreStudentId", studentId)
				.put("scoreTitle", title)
				.put("scoreTypeId", typeId)
				.put("scoreDelete", 0);
		int offset = TableRespone.getOffset(page, size);
		List<BsScore> list = scoreMapper.selectAll(mm, offset, size);
		List<BsScore> count = scoreMapper.selectAll(mm, 0, 0);
		List<BsScoreVo> clist = new ArrayList<BsScoreVo>();
		if(count.size() > 0) {
			for (BsScore score : list) {
				BsStudent s = studentMapper.selectByKey(score.getScoreStudentId());
				BsCourse c = courseMapper.selectByKey(score.getScoreCourseId());
				clist.add(new BsScoreVo(score, s, c));
			}
		}
		return new TableRespone(clist, count.size());
	}

	@Override
	public TableRespone getScoresMore(String scoreId, int page, int size) {
		BsScore info = scoreMapper.selectByKey(scoreId);
		MyMap mm = new MyMap()
				.put("scoreTitle", info.getScoreTitle())
				.put("scoreDelete", 0);
		int offset = TableRespone.getOffset(page, size);
		List<BsScore> list = scoreMapper.selectAll(mm, offset, size);
		List<BsScore> count = scoreMapper.selectAll(mm, 0, 0);
		List<BsScoreVo> clist = new ArrayList<BsScoreVo>();
		if(count.size() > 0) {
			for (BsScore score : list) {
				BsStudent s = studentMapper.selectByKey(score.getScoreStudentId());
				BsCourse c = courseMapper.selectByKey(score.getScoreCourseId());
				clist.add(new BsScoreVo(score, s, c));
			}
		}
		return new TableRespone(clist, count.size());
	}
	
	@Override
	public BaseRespone saveScore(BsScore score) {
		int row = 0;
		BsScore info = scoreMapper.selectByKey(score.getScoreId());
		if(null == info) {
			score.setScoreId(MyTools.getUUID());
			score.setScoreTime(new Date());
			score.setScoreDelete(0);
			row = scoreMapper.insertSelective(score);
			if(row > 0) {
				reLoadScore(score.getScoreId());
			}
		}else {
			row = scoreMapper.updateSelective(score);
		}
		if(row > 0) {
			return BaseRespone.success("保存成功");
		}
		return BaseRespone.error("保存失败");
	}

	@Override
	public BaseRespone reLoadScore(String scoreId) {
		BsScore info = scoreMapper.selectByKey(scoreId);
		Map<String, Object> mm = new HashMap<String, Object>();
		mm.put("targetCourseId", info.getScoreCourseId());
		mm.put("targetDelete", 0);
		List<BsCourseTarget> list = targetMapper.selectAllNotPage(mm);
		if(!MyTools.isEmpty(list)) {
			recordMapper.updateDeleteByScore(scoreId);
			for (BsCourseTarget target : list) {
				BsScoreRecord record = new BsScoreRecord()
						.setRecordId(MyTools.getUUID())
						.setRecordScoreId(scoreId)
						.setRecordTargetId(target.getTargetId())
						.setRecordScore(null)
						.setRecordDelete(0)
						.setRecordTime(new Date());
				recordMapper.insertSelective(record);
			}
			return BaseRespone.success("加载成功");
		}
		return BaseRespone.error("加载失败");
	}
	
	@Override
	public BaseRespone delScore(String scoreId) {
		int row = scoreMapper.deleteUpdate(scoreId, "score_delete");
		if(row > 0) {
			return BaseRespone.success("删除成功");
		}
		return BaseRespone.error("删除失败");
	}
	
	@Override
	public TableRespone getRecords(String scoreId) {
		MyMap mm = new MyMap().put("recordScoreId", scoreId).put("recordDelete", 0);
		List<BsScoreRecord> list = recordMapper.selectAllNotPage(mm);
		List<BsScoreRecordVo> clist = new ArrayList<BsScoreRecordVo>();
		if(list.size() > 0) {
			for (BsScoreRecord record : list) {
				BsCourseTarget t = targetMapper.selectByKey(record.getRecordTargetId());
				clist.add(new BsScoreRecordVo(record, t));
			}
		}
		return new TableRespone(clist, list.size());
	}
	
	@Override
	public BaseRespone saveRecord(BsScoreRecord record) {
		int row = 0;
		BsScoreRecord info = recordMapper.selectByKey(record.getRecordId());
		BsScoreRecord hasrecord = new BsScoreRecord();
		hasrecord.setRecordScoreId(record.getRecordScoreId());
		hasrecord.setRecordTargetId(record.getRecordTargetId());
		BsScoreRecord hasinfo = recordMapper.selectByInfo(hasrecord);
		if(null == info) {
			if(null != hasinfo) {
				return BaseRespone.error("已存在该目标项");
			}
			record.setRecordId(MyTools.getUUID());
			record.setRecordTime(new Date());
			record.setRecordDelete(0);
			row = recordMapper.insertSelective(record);
		}else {
			row = recordMapper.updateSelective(record);
		}
		if(row > 0) {
			if(null != hasinfo && !hasinfo.getRecordId().equals(record.getRecordId())) {
				return BaseRespone.error("已存在该目标项");
			}
			BigDecimal fenzi = new BigDecimal(0);
			BigDecimal fenmu = new BigDecimal(0);
			MyMap mm = new MyMap().put("recordScoreId", record.getRecordScoreId()).put("recordDelete", 0);
			List<BsScoreRecord> rlist = recordMapper.selectAllNotPage(mm);
			try {
				for (BsScoreRecord arecord : rlist) {
					BsCourseTarget t = targetMapper.selectByKey(arecord.getRecordTargetId());
					fenzi = fenzi.add(arecord.getRecordScore().multiply(t.getTargetWeight().divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)));
					fenmu = fenmu.add(t.getTargetScore().multiply(t.getTargetWeight().divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)));
				}
			} catch (Exception e) {
				log.error("达成度计算异常：{}", e);
			}
			if(fenzi.intValue() > 0 && fenmu.intValue() > 0) {
				BsScore appraise = new BsScore();
				appraise.setScoreId(record.getRecordScoreId());
				BigDecimal after = fenzi.divide(fenmu, 2, BigDecimal.ROUND_DOWN);
				appraise.setScoreValue(after);
				scoreMapper.updateSelective(appraise);
			}
			return BaseRespone.success("保存成功");
		}
		return BaseRespone.error("保存失败");
	}
	
	@Override
	public BaseRespone delRecord(String recordId) {
		int row = recordMapper.deleteUpdate(recordId, "record_delete");
		if(row > 0) {
			return BaseRespone.success("删除成功");
		}
		return BaseRespone.error("删除失败");
	}

	@Override
	public BaseRespone saveBatch(List<BsStudentDto> students) {
		List<BsStudent> list = new ArrayList<BsStudent>();
		for (BsStudentDto student : students) {
			BsStudent info = new BsStudent();
			info.setStudentId(MyTools.getUUID())
			.setStudentNumber(student.getStudentNumber())
			.setStudentPassword("123456")
			.setStudentName(student.getStudentName())
			.setStudentCollege(student.getStudentCollege())
			.setStudentClass(student.getStudentClass())
			.setStudentMajor(student.getStudentMajor())
			.setStudentSex(student.getStudentSex())
			.setStudentMobile(student.getStudentMobile())
			.setStudentEmail(student.getStudentEmail())
			.setStudentIntakeTime(student.getStudentIntakeTime())
			.setStudentTime(new Date())
			.setStudentActive(1);
			list.add(info);
		}
		int row = studentMapper.insertBatch(list);
		if(row > 0) {
			return BaseRespone.success("导入成功");
		}
		return BaseRespone.error("导入失败");
	}

	@Override
	public BsStudent getStudentNum(String studentNumber) {
		BsStudent info = studentMapper.selectByInfo(new BsStudent().setStudentNumber(studentNumber));
		return info;
	}
}
